<script>
import { GlDropdown, GlIcon, GlButton } from '@gitlab/ui';
import { VULNERABILITY_STATE_OBJECTS } from '../constants';

export default {
  states: Object.values(VULNERABILITY_STATE_OBJECTS),
  components: { GlDropdown, GlIcon, GlButton },

  props: {
    initialState: { type: String, required: true },
  },

  data() {
    return {
      selected: VULNERABILITY_STATE_OBJECTS[this.initialState],
    };
  },

  computed: {
    initialStateItem() {
      return VULNERABILITY_STATE_OBJECTS[this.initialState];
    },
    buttonText() {
      return this.initialStateItem?.buttonText;
    },
  },

  watch: {
    initialStateItem(newItem) {
      this.selected = newItem;
    },
  },

  methods: {
    changeSelectedState(newState) {
      this.selected = newState;
    },
    closeDropdown() {
      this.$refs.dropdown.hide();
    },
    resetDropdown() {
      this.selected = this.initialStateItem;
    },
    saveState(selectedState) {
      this.$emit('change', selectedState);
      this.closeDropdown();
    },
  },
};
</script>

<template>
  <gl-dropdown
    ref="dropdown"
    data-qa-selector="vulnerability_status_dropdown"
    menu-class="gl-p-0 dropdown-extended-height"
    :text="buttonText"
    :right="true"
    @hide="resetDropdown"
  >
    <li
      v-for="stateItem in $options.states"
      :key="stateItem.action"
      :data-qa-selector="`vulnerability_state_${stateItem.state}`"
      :data-testid="stateItem.state"
      class="py-3 px-2 dropdown-item cursor-pointer border-bottom"
      :class="{ selected: selected === stateItem }"
      @click="changeSelectedState(stateItem)"
    >
      <div class="d-flex align-items-center">
        <gl-icon
          v-if="selected === stateItem"
          class="selected-icon gl-absolute"
          name="status_success_borderless"
          :size="24"
        />
        <div class="pl-4 font-weight-bold">{{ stateItem.dropdownText }}</div>
      </div>
      <div class="pl-4">{{ stateItem.dropdownDescription }}</div>
    </li>

    <template #footer>
      <div class="gl-text-right gl-px-3">
        <gl-button ref="cancel-button" class="mr-2" @click="closeDropdown">
          {{ __('Cancel') }}
        </gl-button>
        <gl-button
          ref="save-button"
          data-qa-selector="vulnerability_save_status_button"
          variant="confirm"
          :disabled="selected === initialStateItem"
          @click="saveState(selected)"
        >
          {{ s__('VulnerabilityManagement|Change status') }}
        </gl-button>
      </div>
    </template>
  </gl-dropdown>
</template>
